package com.itjin.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/download")
@Tag(name = "下载控制器")
@Slf4j
public class DownloadController {

  @Value("${file.upload.path:/tmp/uploads}")
  private String uploadPath;

  @GetMapping("/{platform}/{date}/{fileName:.+}")
  @Operation(summary = "下载文件")
  public ResponseEntity<Resource> downloadFile(
      @PathVariable String platform,
      @PathVariable String date,
      @PathVariable String fileName) {
    try {
      // 构建文件路径
      Path filePath = Paths.get(uploadPath, platform, date, fileName);
      File file = filePath.toFile();

      if (!file.exists()) {
        return ResponseEntity.notFound().build();
      }

      // 确定文件的MIME类型
      String contentType;
      try {
        contentType = Files.probeContentType(filePath);
      } catch (IOException e) {
        contentType = "application/octet-stream";
      }

      if (contentType == null) {
        contentType = "application/octet-stream";
      }

      // 创建资源
      Resource resource = new FileSystemResource(file);

      // 设置响应头
      return ResponseEntity.ok()
          .contentType(MediaType.parseMediaType(contentType))
          .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
          .body(resource);
    } catch (Exception e) {
      log.error("文件下载失败", e);
      return ResponseEntity.internalServerError().build();
    }
  }
}